import React, { useRef, useEffect, useState } from 'react';
import { Button, Modal, Card, message } from 'antd';

const SignatureButton: React.FC = () => {
  const [isModalVisible, setIsModalVisible] = useState<boolean>(false);
  const canvasRef = useRef<HTMLCanvasElement | null>(null);
  const isDrawing = useRef<boolean>(false);
  let context: CanvasRenderingContext2D | null = null;

  // 初始化画布
  useEffect(() => {
    const canvas = canvasRef.current;
    if (canvas) {
      context = canvas.getContext('2d');
      if (context) {
        context.lineWidth = 2;
        context.lineCap = 'round';
        context.strokeStyle = '#000';
      }

      // 自适应画布大小
      const resizeCanvas = () => {
        if (canvas) {
          canvas.width = canvas.offsetWidth;
          canvas.height = canvas.offsetHeight;
        }
      };
      resizeCanvas();
      window.addEventListener('resize', resizeCanvas);
      return () => window.removeEventListener('resize', resizeCanvas);
    }
  }, [isModalVisible]);

  // 获取坐标（兼容鼠标和触摸事件）
  const getCoordinates = (
    e: React.MouseEvent<HTMLCanvasElement> | React.TouchEvent<HTMLCanvasElement>
  ): { offsetX: number; offsetY: number } => {
    const canvas = canvasRef.current!;
    let offsetX: number, offsetY: number;
    if (e.type.includes('touch')) {
      const rect = canvas.getBoundingClientRect();
      offsetX = (e as React.TouchEvent<HTMLCanvasElement>).touches[0].clientX - rect.left;
      offsetY = (e as React.TouchEvent<HTMLCanvasElement>).touches[0].clientY - rect.top;
    } else {
      offsetX = (e as React.MouseEvent<HTMLCanvasElement>).nativeEvent.offsetX;
      offsetY = (e as React.MouseEvent<HTMLCanvasElement>).nativeEvent.offsetY;
    }
    return { offsetX, offsetY };
  };

  // 鼠标/触摸事件
  const startDrawing = (e: React.MouseEvent<HTMLCanvasElement> | React.TouchEvent<HTMLCanvasElement>) => {
    isDrawing.current = true;
    if (context) {
      context.beginPath();
      const { offsetX, offsetY } = getCoordinates(e);
      context.moveTo(offsetX, offsetY);
    }
  };

  const draw = (e: React.MouseEvent<HTMLCanvasElement> | React.TouchEvent<HTMLCanvasElement>) => {
    if (!isDrawing.current || !context) return;
    const { offsetX, offsetY } = getCoordinates(e);
    context.lineTo(offsetX, offsetY);
    context.stroke();
  };

  const stopDrawing = () => {
    isDrawing.current = false;
    if (context) {
      context.closePath();
    }
  };

  // 清空画布
  const clearCanvas = () => {
    const canvas = canvasRef.current;
    if (canvas && context) {
      context.clearRect(0, 0, canvas.width, canvas.height);
      message.success('签名已清空');
    }
  };

  // 保存签名
  const saveSignature = () => {
    const canvas = canvasRef.current;
    if (canvas) {
      const dataURL = canvas.toDataURL('image/png');
      const link = document.createElement('a');
      link.href = dataURL;
      link.download = 'signature.png';
      link.click();
      message.success('签名已保存');
      setIsModalVisible(false);
    }
  };

  // 打开 Modal
  const showModal = () => {
    setIsModalVisible(true);
  };

  // 关闭 Modal
  const handleCancel = () => {
    setIsModalVisible(false);
  };

  return (
    <>
      <Button type="primary" onClick={showModal}>
        打开签名
      </Button>
      <Modal
        title="电子签名"
        open={isModalVisible}
        onCancel={handleCancel}
        footer={null}
        width={600}
      >
        <Card>
          <div style={{ position: 'relative', width: '100%', height: 300 }}>
            <canvas
              ref={canvasRef}
              style={{ border: '1px solid #d9d9d9', width: '100%', height: '100%', backgroundColor: '#fff', touchAction: 'none' }}
              onMouseDown={startDrawing}
              onMouseMove={draw}
              onMouseUp={stopDrawing}
              onMouseLeave={stopDrawing}
              onTouchStart={startDrawing}
              onTouchMove={draw}
              onTouchEnd={stopDrawing}
            />
          </div>
          <div style={{ marginTop: 16, textAlign: 'center' }}>
            <Button type="primary" onClick={saveSignature} style={{ marginRight: 8 }}>
              保存签名
            </Button>
            <Button onClick={clearCanvas}>清空</Button>
          </div>
        </Card>
      </Modal>
    </>
  );
};

export default SignatureButton;
